package com.cweb.admin.model.demo.controller;

import com.cweb.framework.pojo.CustomException;
import com.cweb.admin.configuration.MyWebContextFactory;
import com.cweb.admin.configuration.database.DataSourceDTO;
import com.cweb.admin.configuration.database.DataSourceUtil;
import com.cweb.admin.configuration.database.DynamicDataSourceContextHolder;
import com.cweb.admin.configuration.database.DynamicRoutingDataSource;
import com.cweb.admin.model.demo.mapper.DynamicDatabasesMapper;
import com.youbenzi.md2.util.MDUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

@RestController
public class TestController {

    @Autowired
    private DynamicDatabasesMapper dynamicDatabasesMapper;

    // 追加数据库
    @RequestMapping("post")
    public String post() throws CustomException, WxErrorException {
        return MDUtil.markdown2Html("[**开源中国**](http://www.oschina.net)社区，是一个很不错的网站。欢迎上去查找开源软件，吐吐槽！");
    }

    // 追加数据库
    @RequestMapping("addDb")
    public void addDb() throws CustomException, WxErrorException {
        DataSourceBuilder.create().build();
    }

    @RequestMapping("selectDemo")
    public Object selectDemo() throws CustomException, WxErrorException {
        return dynamicDatabasesMapper.showDatabases();
    }
    @RequestMapping("selectDemo2")
    public Object selectDemo2() throws CustomException, WxErrorException {
        return dynamicDatabasesMapper.find();
    }

    // 添加数据库
    @RequestMapping(value = "addDataSource")
    public String addDataSource(HttpServletRequest request){
        //获取spring中的动态数据源bean
        DataSourceDTO dataSourceDTO = new DataSourceDTO();
        dataSourceDTO.setDbKey("third");
        dataSourceDTO.setAddr("localhost");
        dataSourceDTO.setDbName("test");
        dataSourceDTO.setPort(9201);
        dataSourceDTO.setUsername("changfan");
        dataSourceDTO.setPassword("fanfan12");

        // 追加数据库元
        DataSource dataSource = DataSourceUtil.initDataSource(dataSourceDTO);
        DynamicDataSourceContextHolder.addMonitor(dataSourceDTO.getDbKey(), dataSource);
        // 切换
        DynamicDataSourceContextHolder.setDataSourceKey(dataSourceDTO.getDbKey());
        // 启动配置
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) MyWebContextFactory.getBean("dynamicDataSource");
        dynamicRoutingDataSource.afterPropertiesSet();
        return "添加成功";
    }
}
